package com.fy56.platform.logistics.restful.api.controller.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.restful.api.app.authorization.annotation.Authorization;
import com.fy56.platform.logistics.service.wx.ICompanyInfoService;
import com.fy56.platform.logistics.service.wx.IGoodsTraceService;
import com.fy56.platform.logistics.utils.DateUtil;
import com.fy56.platform.logistics.utils.HttpClientUtils;
import com.fy56.platform.logistics.utils.StaticUtil;
import com.fy56.platform.logistics.utils.StringUtil;
import com.google.common.collect.Maps;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.Map;

/**
 * 货物跟踪信息RestController
 * Created by li on 2018-02-01 16:05
 */
@Api(value = "GoodsTrace", description = "货物跟踪信息", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/trace")
public class GoodsTraceController {

	@Autowired
	private ICompanyInfoService iCompanyService;

	@Autowired
	private IGoodsTraceService iGoodsTraceService;

	private static final Logger log = Logger.getLogger(GoodsTraceController.class);

	@RequestMapping(value = "/toSearchGoodsTraces", method = RequestMethod.GET)
	public void  toSearchGoodsTraces(@RequestParam String param,HttpServletRequest request , HttpServletResponse response) {
		String errMsg = null;
		String result = null;
		Map<String,Object> resultMap = null;
		Map<String,Object> content = Maps.newHashMap();
		try {
			Map<String,String> params = Maps.newHashMap();
			if (StringUtils.isNotEmpty(param)){
				String paramArr [] = param.split(",");
				if (paramArr!=null&&paramArr.length>1){
					params.put("code",paramArr[0]);
					params.put("orderNumber",paramArr[1]);
				}
				result = HttpClientUtils.postParameters(StaticUtil.TRACE_DETAILS_URL, setParam(makeParam(params)));
				if(StringUtils.isNotEmpty(result)){
					resultMap = JSON.parseObject(result);;
					if(Boolean.valueOf(resultMap.get("success").toString())){
						reset(content,resultMap.get("object").toString());
					}
				}else{
					errMsg = "请求失败或无返回值";
				}
			}
		} catch (JSONException e) {
			errMsg = "参数出错";
		} catch (SocketTimeoutException e) {
			errMsg = "请求货物跟踪平台超时！";
		}  catch (Exception e) {
			errMsg = "服务端出错！";
		} finally {
			HttpSession session = request.getSession();
			session.setAttribute("content",content);
			result = null;
			resultMap = null;
		}
		try {
			// TODO 对应 [main/webapp/html/trace/goods.jsp]
			response.sendRedirect("goods.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/searchGoodsTraces", method = RequestMethod.POST)
	@ApiOperation(value = "获取货物跟踪信息")
	@Authorization
	public ResponseEntity searchGoodsTraces(@RequestParam String param) {
		String errMsg = null;
		String result = null;
		Map<String,Object> resultMap = null;
		Map<String,Object> content = Maps.newHashMap();
		try {
			result = HttpClientUtils.postParameters(StaticUtil.TRACE_DETAILS_URL, setParam(makeParamMap(param)));
			if(StringUtils.isNotEmpty(result)){
				resultMap = JSON.parseObject(result);;
				if(Boolean.valueOf(resultMap.get("success").toString())){
					reset(content,resultMap.get("object").toString());
				}
			}else{
				errMsg = "请求失败或无返回值";
			}
		} catch (JSONException e) {
			errMsg = "参数出错";
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "参数出错！"), HttpStatus.OK);
		} catch (SocketTimeoutException e) {
			errMsg = "请求货物跟踪平台超时！";
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "请求货物跟踪平台超时！"), HttpStatus.OK);
		}  catch (Exception e) {
			errMsg = "服务端出错！";
		} finally {
			result = null;
			resultMap = null;
			if(errMsg != null){
				return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, errMsg), HttpStatus.OK);
			}else{
				return new ResponseEntity(ResultModel.ok(content), HttpStatus.OK);
			}
		}
	}

	private Map<String,String> makeParamMap(String param){
		Map<String,Object> map = JSON.parseObject(param);
		Map<String,String> result = Maps.newHashMap();
		//发货人手机号
		result.put("consignorTelephoneNumber",map.get("mobile") == null ? "" : map.get("mobile").toString());
		//票号
		result.put("shippingNoteNumber",map.get("orderNumber") == null ? "" : map.get("orderNumber").toString());
		//金融代码
		result.put("headTenant",map.get("code") == null ? "" : map.get("code").toString());
		//开始日期
		result.put("startDate", StringUtil.objIsEmpty(map.get("startDate")) ? DateUtil.getOneMonthAgo(DateUtil.getNowTime("yyyy-MM-dd")) + " 00:00:00" : map.get("startDate").toString());
		//结束日期
		result.put("endDate",StringUtil.objIsEmpty(map.get("endDate")) ? DateUtil.getNowTime("yyyy-MM-dd") + " 23:59:59" : map.get("endDate").toString());
		return result;
	}
	private Map<String,String> makeParam(Map<String,String>  map){
		Map<String,String> result = Maps.newHashMap();
		//发货人手机号
		result.put("consignorTelephoneNumber",map.get("mobile") == null ? "" : map.get("mobile").toString());
		//票号
		result.put("shippingNoteNumber",map.get("orderNumber") == null ? "" : map.get("orderNumber").toString());
		//金融代码
		result.put("headTenant",map.get("code") == null ? "" : map.get("code").toString());
		//开始日期
		result.put("startDate", StringUtil.objIsEmpty(map.get("startDate")) ? DateUtil.getOneMonthAgo(DateUtil.getNowTime("yyyy-MM-dd")) + " 00:00:00" : map.get("startDate").toString());
		//结束日期
		result.put("endDate",StringUtil.objIsEmpty(map.get("endDate")) ? DateUtil.getNowTime("yyyy-MM-dd") + " 23:59:59" : map.get("endDate").toString());
		return result;
	}
	/**
	 * 把对象封装成map做为参数传给平台
	 *
	 * @param map
	 * @return
	 */
	private String setParam(Map<String,String> map){
		String param = "param="+ JSONObject.toJSONString(map);
		return param;
	}

	private void reset(Map<String,Object> contentMap,String content){
		JSONArray array = JSON.parseObject(content).getJSONArray("list");
		List<Map<String,Object>> mapListJson = (List)array;
		Company company = null;
		String companyName = "";
		String companyPhone = "";
		for(Map<String,Object> map : mapListJson){
			for (String key : map.keySet()) {
				if("headTenant".equals(key) && StringUtil.isNotEmpty(map.get(key).toString())){
					company = iCompanyService.getCompanyByCode(map.get(key).toString());
					if(company != null){
						companyName = company.getName();
						companyPhone = company.getPhone();
					}
					break;
				}
			}
			map.put("companyName",companyName);
			map.put("companyPhone",companyPhone);
		}
		contentMap.put("list",mapListJson);
	}

	@RequestMapping(value = "/getGoodsTracesInfo", method = RequestMethod.POST)
	@ApiOperation(value = "获取货物跟踪信息")
	@Authorization
	public ResponseEntity getGoodsTracesFromBSOrF6(@RequestParam String code,@RequestParam String orderNo) {
		try {
			return new ResponseEntity(ResultModel.ok(iGoodsTraceService.getGoodsTracesFromBSOrF6(code,orderNo)), HttpStatus.OK);
		} catch (Exception e) {
			log.error("获取货物跟踪信息失败" + e.getMessage(),e);
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, e.getMessage() == null ? "获取货物跟踪信息失败" : e.getMessage()), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/getGoodsTracesFromTrack", method = RequestMethod.POST)
	@ApiOperation(value = "获取货物跟踪信息")
	@Authorization
	public ResponseEntity getGoodsTracesFromTrack(@RequestParam String trackingNo) {
		try {
			return new ResponseEntity(ResultModel.ok(iGoodsTraceService.getGoodsTracesFromTrack(trackingNo)), HttpStatus.OK);
		} catch (Exception e) {
			log.error("获取货物跟踪信息失败" + e.getMessage(),e);
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, e.getMessage() == null ? "获取货物跟踪信息失败" : e.getMessage()), HttpStatus.OK);
		}
	}

}